﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using LEDControllerTools.Controller;

namespace LedController
{
    public partial class frmLedPanelView : Form, IControllableView
    {
        public event IssueDigitalCommandHandler IssueDigitalCommand;
        public event RequestBatteryCommandHandler RequestBattery;

        public frmLedPanelView()
        {
            InitializeComponent();
            //Extra initialisation

            //set 7 segment LED font for battery voltage
            var res = Properties.Resources._7_segment_display;
            PrivateFontCollection fonts;
            FontFamily family = Fonts.FontHelper.LoadFontFamily(res, out fonts);
            var lcdFont =  new Font(family, 36.0f, FontStyle.Bold);
            lblBattery.Font = lcdFont;
            lblBattery.ForeColor = Color.Red;
            lblBattery.BackColor = Color.Transparent;
            lblBattery.Dock=DockStyle.Fill;
            lblBattery.TextAlign=ContentAlignment.MiddleCenter;


            foreach (var led in ledPanel1.Leds.Values)
            {
                led.MouseClick += led_Click;
            }
        

        }

        //IO Commands
        void led_Click(object sender, EventArgs e)
        {
            var led = ((LedBulb) sender);
            OnIssueDigitalCommand(sender, new DigitalOutCommandEventArgs(led.Name, !led.On));
        }

        public void OnIssueDigitalCommand(object sender, DigitalOutCommandEventArgs e)
        {
            if (IssueDigitalCommand != null)
                IssueDigitalCommand(sender, e);
        }

        public void Controller_PinToggled(object sender, ToggledEventArgs e)
        {
            var led = (LedBulb)ledPanel1.Controls.Find(sender.ToString(), true)[0];
            led.On = e.IsOn;
        }


        //Battery commands
        private void lblBattery_Click(object sender, EventArgs e)
        {
            OnRequestBattery(sender, new EventArgs());
        }

        public void OnRequestBattery(object sender, EventArgs e)
        {
            if (RequestBattery != null)
                RequestBattery(sender, e);
        }

        public void Controller_BatteryUpdate(object sender, BatteryVoltageEventArgs e)
        {
            var battery = Math.Round(e.Voltage, 3);
            string batteryText = battery.ToString("#.000"); // running on worker thread
            try
            {
                this.Invoke((MethodInvoker)delegate
                {
                    lblBattery.Text = batteryText; // runs on UI thread
                });
                
            }
            catch{}

        }


    }
}
